using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;

namespace net.notdot.Attercop {
    [Serializable()]
    public class SearchMessage : Message, UdpMessage {
        public readonly int Id;
        public readonly string Keywords = "";
        public readonly long MinSize;
        public readonly long MaxSize;
        public readonly string MimeType = "";
        public readonly bool? IsDir;

        static SearchMessage() { ClientInstance.AddMessageHandler<SearchMessage>(); }

        public SearchMessage(MessageAddressing addressing, int Id, string keywords, long minSize, long maxSize, string MimeType, bool? IsDir)
            : base(addressing) {
            this.Id = Id;
            this.Keywords = keywords;
            this.MinSize = minSize;
            this.MaxSize = maxSize;
            this.MimeType = MimeType;
            this.IsDir = IsDir;
        }

        protected SearchMessage(MessageReader reader)
            : base(reader)
        {
            reader.BeginRegion();
            reader.ReadByte();  //Version
            this.Id = reader.ReadInt32();
            this.Keywords = reader.ReadString();
            this.MinSize = reader.ReadInt64();
            this.MaxSize = reader.ReadInt64();
            this.MimeType = reader.ReadString();
            byte dir = reader.ReadByte();
            if (dir == 255)
            {
                IsDir = null;
            }
            else
            {
                IsDir = (dir == 0) ? false : true;
            }
            reader.EndRegion();
        }

        public override void Serialize(MessageWriter writer)
        {
            base.Serialize(writer);

            writer.BeginRegion();
            writer.Write((byte)0);  //Version
            writer.Write(this.Id);
            writer.Write(this.Keywords);
            writer.Write(this.MinSize);
            writer.Write(this.MaxSize);
            writer.Write(this.MimeType);
            if (!IsDir.HasValue)
            {
                writer.Write((byte)255);
            }
            else
            {
                writer.Write(IsDir.Value ? 1 : 0);
            }
            writer.EndRegion();
        }

        public virtual void Handle(ClientInstance c) {
            if (this.PeerState != PeerState.Introduced)
                return;

            if (c.SearchHandler != null)
            {                
                IList<SearchResult> results = c.SearchHandler(this);
                if (results != null && results.Count > 0)
                {
                    c.SendMessage(new SearchResultMessage(new MessageAddressing(c.LocalPeer.Address, c.NetworkSettings.NetworkAddress), this, results));
                }
            }
        }
    }
}
